package com.springapp.symm.controller;

import com.springapp.sqlite.ConfigModel;
import com.springapp.symm.bean.DetailedPOJO;
import com.springapp.symm.bean.IndexPOJO;
import com.springapp.symm.service.GithubManager;
import com.springapp.utils.GlobalUtils;
import com.springapp.utils.FileTools;
import org.markdown4j.Markdown4jProcessor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tandan
 * @Date 17-3-21
 * @see
 */
@Controller
@RequestMapping("/IndexCon")
public class IndexCon {


    @RequestMapping(value = {"index",""})
    public String printWelcome(ModelMap model, HttpServletRequest request, HttpServletResponse response) {

        List<IndexPOJO> list = new ArrayList();
        String appReadme = "";

        //1基础模板文件
        String templatesPath = GlobalUtils.getBasePath()+File.separator+"templates";
        if(FileTools.judgeIsFolderExist(templatesPath,false)){
            File file = new File( templatesPath ); //读取指定目录下的文件数量
            list.addAll(this.getModelInfo( file.listFiles(),"templates" ));
        }

        //2应用架构文件
         templatesPath = GlobalUtils.getBasePath()+File.separator+"infra-templates";
        if(FileTools.judgeIsFolderExist(templatesPath,false)){
            File file = new File( templatesPath ); //读取指定目录下的文件数量
            list.addAll(this.getModelInfo( file.listFiles(),"infra-templates"));
        }


        appReadme =  FileTools.readTxtFile( GlobalUtils.getBasePath() + File.separator  +"README.md");
        model.addAttribute("list",list);
        try {
            appReadme = new Markdown4jProcessor().process(appReadme);
        } catch (IOException e) {
            e.printStackTrace();
        }

        model.addAttribute("appReadme",appReadme);

        return "IndexCon";
    }

    @RequestMapping(value = {"appDelete"})
    public String appDelete(ModelMap model, HttpServletRequest request, HttpServletResponse response) {

        Map map = new HashMap();
        String result = "success";
        String desc= "";

        try {
            //获得路径
            String templatesType = request.getParameter("templatesType");
            String catalog = request.getParameter("catalog");
            String fullPath  = GlobalUtils.getBasePath() + File.separator + templatesType + File.separator + catalog;
            //执行删除
            boolean bl = FileTools.deleteDirectory(fullPath);
            if(bl){
                //提交，同步到github
                new GithubManager().removeFile( templatesType + "/" + catalog );
                desc="删除应用成功";
            }else{
                result="fail";
                desc="删除不成功，请重新更新项目或者联系管理人员";
            }
        }catch (Exception e){
            e.printStackTrace();
            result="fail";
            desc="出现异常,请联系客服; 异常:"+e.toString();
        }
        ModelAndView modelView = new ModelAndView();
        map.put("result",result);
        map.put("desc",desc);
        modelView.addAllObjects(map);

        print(response, result);
        return null;
    }

    /**
     *
     * @param fileLists
     * @param templatesType  'templates' or  'infra-templates'
     * @return
     */
    public  List<IndexPOJO> getModelInfo(File[] fileLists , String templatesType){
        String templatesPath = GlobalUtils.getBasePath()+File.separator+templatesType;
        List<IndexPOJO> list = new ArrayList();
        for (int i = 0; i < fileLists.length; i++) { // 循环遍历这个集合内容
            File eleFile = fileLists[i];
            IndexPOJO pojo = new IndexPOJO();
            pojo.setFileName(eleFile.getName());

            String sPath = "";
            File svgFile  = new File ( templatesPath + File.separator +  eleFile.getName());
            File[] svgFiles = svgFile.listFiles();
            for(int j = 0; j < svgFiles.length; j++){
                if(svgFiles[j].getName().indexOf("catalogIcon")>=0){
                    sPath = GlobalUtils.getProjectName()  + File.separator + templatesType +  File.separator  + eleFile.getName() + File.separator  + svgFiles[j].getName();
                }
            }
            //String level2Cato = GlobalUtils.getFullPath() + File.separator + eleFile.getName();
            //sPath = GlobalUtils.getInspectCatalog() + File.separator  + eleFile.getName() + File.separator  + "catalogIcon-"+eleFile.getName()+".svg";
            pojo.setSvgPath(sPath);

            String configFile = ( templatesPath + File.separator + eleFile.getName() + File.separator + "config.yml" );
            pojo.setConfig(FileTools.readTxtFile(configFile));

            String verPath = templatesPath + File.separator + eleFile.getName() ;
            pojo.setVerInfo(this.getVerion(verPath));

            pojo.setTemplatesType(templatesType);
            list.add(pojo);
        }
        return list;
    }

    //通过目录，获得该目录下所拥有的所有版本信息
    //
    public List<DetailedPOJO>  getVerion(String verPath){
        List<DetailedPOJO> list = new ArrayList<DetailedPOJO>();
        File file = new File(verPath);
        File[] fileLists = file.listFiles(); // 如果是目录，获取该目录下的内容集合
        for (int i = 0; i < fileLists.length; i++) { // 循环遍历这个集合内容
            if (fileLists[i].isDirectory()) {
                DetailedPOJO detailedPOJO = new DetailedPOJO();
                detailedPOJO.setVerion(fileLists[i].getName());
                String dcFile = verPath + File.separator + fileLists[i].getName() + File.separator + "docker-compose.yml";
                String rcFile = verPath + File.separator + fileLists[i].getName() + File.separator + "rancher-compose.yml";
                detailedPOJO.setDockerCompose( FileTools.readTxtFile(dcFile) );
                detailedPOJO.setRancherCompose(  FileTools.readTxtFile(rcFile)  );
                list.add(detailedPOJO);
            }
        }
        return list;
    }


    public void print(HttpServletResponse response, String content) {
        try {

            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            PrintWriter write = response.getWriter();
            write.print(content);
            write.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
